package com.sog.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sog.entity.Admin;
import com.sog.service.AdminServiceI;
import com.sog.service.AdminServiceImpl;

/**
 * 
 * @类名 AdminServlet
 * @描述 TODO(一句话描述类的作用)
 * @作者 王帅
 * @日期 2018年6月26日 下午2:56:44
 *
 */
@WebServlet("/AdminLogin")
public class AdminServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		AdminServiceI asi = new AdminServiceImpl();
		String login=request.getParameter("login");
		if("out".equals(login)){
			//销毁session
			HttpSession session = request.getSession();
			session.invalidate();
			response.sendRedirect("/login.html");
			
		}else{
			try {
				List<Admin> list = asi.findByAll();
				//通过 requset 将获取到的数据传递给页面
				request.setAttribute("list", list);
				//请求转发
				request.getRequestDispatcher("/admin.jsp").forward(request, response);
				
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * view界面跳转到该方法
	 * 该方法会调用 业务层方法进行用户密码认证
	 * */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println(username+":"+password);
		//创建 业务层对象
		AdminServiceI asi = new AdminServiceImpl();
		try {
			//判断用户名密码是否正确
			if(asi.login(username, password)) {
				//获取会话，将用户值放入会话中
				HttpSession session=request.getSession();
				session.setAttribute("username", username);
				/*********添加登录日志***************/
				//LogsServiceI lsi = new LogsServiceImpl();
				//Logs logs = new Logs();
				//logs.setOperateType(0);
				//logs.setContent(username+"登陆成功.");
				//lsi.add(logs);
				
				response.sendRedirect("/index.jsp");
			}else {
				response.sendRedirect("/error.jsp");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
